package com.zhengsr.latte.ui.recycler.adapter;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseIntArray;
import android.view.ViewGroup;

import com.zhengsr.latte.ui.recycler.adapter.base.RBaseAdapter;
import com.zhengsr.latte.ui.recycler.adapter.base.RBaseViewholder;

import java.util.ArrayList;
import java.util.List;

/**
 *@author zhengshaorui
 */
public abstract class RMultiAdapter<T extends RMultiBean> extends RBaseAdapter {
    private static final String TAG = "zsr";
    private SparseIntArray mLayouts ;
    private List<T> mData = new ArrayList<>();
    private Context mContext;

    public RMultiAdapter(Context context, List<T> beans) {
        mContext = context;
        mData.clear();
        mData.addAll(beans);

    }

    /**
     * 这个是必须要写的，需要添加不同 viewtype，对应的 layoutid
     * @param type
     * @param layoutid
     */
    public void addItemType(int type,@LayoutRes int layoutid){
        if (mLayouts == null){
            mLayouts = new SparseIntArray();
        }
        mLayouts.put(type,layoutid);
    }


    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        GridLayoutManager manager = (GridLayoutManager) recyclerView.getLayoutManager();
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return mData.get(position).getSpanSize();
            }
        });
    }

    @Override
    public RBaseViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
        RBaseViewholder viewholder = RBaseViewholder.getViewHolder(parent.getContext(),
                mLayouts.get(viewType),parent);
        //放在这里，避免重复调用实例
        bindClickListener(viewholder,this);
        return  viewholder;

    }

    @Override
    public void onBindViewHolder(RBaseViewholder holder, int position) {
        getConver(holder,mData.get(position),position);
    }
    protected abstract void getConver(RBaseViewholder holder, T data, int position);


    @Override
    public int getItemCount() {
        return mData.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mData.get(position).getItemType();
    }



}